package com.xb.loan.encryptor.mina.encoder;


import com.xb.loan.encryptor.bean.Packet;
import com.xb.loan.util.binaryConvert.parse.str.StringParser;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.apache.mina.filter.codec.demux.MessageEncoder;

import java.util.List;

public class BinaryEncoder implements MessageEncoder<Packet> {

	private StringParser parser = new StringParser();
	
	@Override
	public void encode(IoSession session, Packet bean, ProtocolEncoderOutput out)
			throws Exception {
		// transcode
		byte[] transcode = parser.format(bean.getTranscode(), null);
		
		byte[] body = convert(bean.getPacketBody());
		
		IoBuffer buf = IoBuffer.allocate(body.length + transcode.length + 4);

		buf.putShort((short) (body.length + transcode.length + 2));
		
		buf.put(bean.getProtocolMajor());
		
		buf.put(bean.getProtocolMinor());

		buf.put(transcode);
		
		buf.put(body);
		
//		byte[] array = buf.array();
		
		buf.flip();
		
		out.write(buf);
	}
	
	private byte[] convert(List<Byte> body){
		
		byte[] bits = new byte[body.size()];
		
		for(int i=0;i<bits.length;i++){
			
			bits[i] = body.get(i);
		}
		
		return bits;
	}

}
